<?php
// ANCIENS CONTROLLER DE FACTURATION FIXE
return;

require_once("dao/Dao.php");
require_once("dao/ClientDao.php");
require_once("dao/CommandeDao.php");
if ($_SESSION['niveauAuth'] == '1' or $_SESSION['niveauAuth'] == '3' or $_SESSION['niveauAuth'] == '4'or $_SESSION['niveauAuth'] == '7' or $_SESSION['niveauAuth'] == '8') {
    $requete_supp = $bdd->prepare("DELETE  FROM `admin_facture` WHERE type = 'fixe' ");
    $requete_supp->execute() or exit(print_r($bdd->errorInfo()));

//$requete = $bdd->prepare(" SELECT * FROM fiche_client WHERE code_client_hto = '306141'");
    $requete    = $bdd->prepare(" SELECT * FROM fiche_client ");
    $requete->execute();
    $infoclient = $requete->fetchall(PDO::FETCH_ASSOC);
    $requete->closeCursor();

    class DateTimeFrance extends DateTime {

        public function format($format) {
            $english = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
            $france  = array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre');
            return str_replace($english, $france, parent::format($format));
        }

    }

    function format_time($t, $f = ':') { // t = seconds, f = separator 
        return sprintf("%02d%s%02d%s%02d", floor($t / 3600), $f, ($t / 60) % 60, $f, $t % 60);
    }

    function tri_type($t) {
        global $tab_op_mobile, $tab_op_fixe;
        if (in_array($t, $tab_op_mobile)) {
            return "mobile";
        } elseif (in_array($t, $tab_op_fixe)) {
            return "fixe";
        } else {
            return "autre";
        }
    }

// récupération du pied de page 
    $myFile  = "facture.txt";
    $fh      = fopen($myFile, 'r');
    $contenu = fread($fh, filesize($myFile));
    fclose($fh);

//chargement de la tarification 
    $requete      = $bdd->prepare(" SELECT * FROM vga_table_prix ");
    $requete->execute();
    $x            = 0;
    while ($tarification = $requete->fetch(PDO::FETCH_OBJ)) {
        $tab_tarification_vga[$tarification->destination]['tarif_1']  = $tarification->tarif_1;
        $tab_tarification_vga[$tarification->destination]['tarif_2']  = $tarification->tarif_2;
        $tab_tarification_vga[$tarification->destination]['tarif_3']  = $tarification->tarif_3;
        $tab_tarification_vga[$tarification->destination]['tarif_4']  = $tarification->tarif_4;
        $tab_tarification_vga[$tarification->destination]['tarif_5']  = $tarification->tarif_5;
        $tab_tarification_vga[$tarification->destination]['relation'] = $tarification->relation;
    }
    $requete->closeCursor();

    /* $requete = $bdd->prepare(" SELECT * FROM voip_table_prix ");
      $requete->execute();
      $x=0;
      while( $tarification = $requete->fetch(PDO::FETCH_OBJ) )
      {
      $tab_tarification_voip[$tarification->id]['tarif_1'] = $tarification->tarif_1;
      $tab_tarification_voip[$tarification->id]['tarif_2'] = $tarification->tarif_2;
      $tab_tarification_voip[$tarification->id]['tarif_3'] = $tarification->tarif_3;
      $tab_tarification_voip[$tarification->id]['tarif_4'] = $tarification->tarif_4;
      $tab_tarification_voip[$tarification->id]['tarif_5'] = $tarification->tarif_5;
      }
      $requete->closeCursor(); */

    $requete      = $bdd->prepare(" SELECT * FROM fax_table_prix ");
    $requete->execute();
    $x            = 0;
    while ($tarification = $requete->fetch(PDO::FETCH_OBJ)) {
        $tab_tarification_fax['tarif'] = $tarification->cost;
    }
    $requete->closeCursor();

//traitement client par client	
    foreach ($infoclient as $cle => $donneesclients) {
        //détail client avec une date de souscription
        $requete       = $bdd->prepare(" SELECT * FROM `detail_client` 
								WHERE code_client_hto= " . $donneesclients['code_client_hto'] . " 
								AND date_souscription <>'' 
								AND (type_offre = 'vga' or type_offre = 'voip' or type_offre = 'xdsl') GROUP BY ndi ORDER BY type_offre");
        $requete->execute();
        $detail_client = $requete->fetchall(PDO::FETCH_ASSOC);
        $requete->closeCursor();

        $total                       = array();
        $tab_forfait                 = array();
        $tab_lignes                  = array();
        $prix_total_forfaits         = 0;
        $temps_restant               = 0;
        $tab_consos                  = array();
        $tab_details                 = array();
        $tab_consos['total_facture'] = 0;
        $data['cout_reel']           = 0;
        $tab_equipement              = array();
        $tab_op_mobile               = array(0 => "France - Mobile Bouygues", 1 => "France - Mobile Free", 2 => "France - Mobile Orange", 3 => "France - Mobile SFR", 4 => "France [BOUYGUES] [MOB]", 5 => "France [ORANGE] [MOB]", 6 => "France [SFR] [MOB]", 7 => "France [MOB]");
        $tab_op_fixe                 = array(0 => "France - Local/National", 1 => "France [FIX]");

        $mois_precedent = date("Y-m-j H:i:s", strtotime('23:59 last day of last month'));  //mois précédent
        $mois_suivant   = date("Y-m-j H:i:s", mktime(0, 0, 0, date("m") + 1, 1, date("Y"))); //mois suivant

        if ($detail_client <> null) {
            // informations
            $code_client               = $donneesclients['code_client_hto'];
            $code_client_voip          = $donneesclients['code_client_voip'];
            $id_client                 = $donneesclients['id'];
            $reduction_abonnement_voip = $donneesclients['abonnement_voip'];
            $reduction_abonnement_vga  = $donneesclients['abonnement_vga'];
            $reduction_abonnement_voip = $donneesclients['abonnement_voip'];
            $reduction_minute_vga      = $donneesclients['minute_vga'];
            $reduction_minute_voip     = $donneesclients['minute_voip'];
            if (!empty($donneesclients['grille_tarifaire_voip'])) {
                $grille_tarifaire_voip = $donneesclients['grille_tarifaire_voip'];
            } else {
                $grille_tarifaire_voip = 'tarif_1';
            }
            if (!empty($donneesclients['grille_tarifaire_vga'])) {
                $grille_tarifaire_vga = $donneesclients['grille_tarifaire_vga'];
            } else {
                $grille_tarifaire_vga = 'tarif_1';
            }
            $totaldonnees     = array();
            $facture_total_HF = 0;

            //calcul période
            $debut_mois_prec             = strtotime('00:00 first day of last month');    //début du mois précédent
            $fin_mois_prec               = strtotime('23:59 last day of last month');    //fin du mois précédent
            $date_en_cours               = strtotime('today');         //mois en cours
            $date_souscription_mois_suiv = strtotime('first day of next month'); //mois suivant
            // ----------------------------------   EQUIPEMENT  ------------------------------------------
            $requete = $bdd->prepare(" SELECT * FROM `commande_equipement_fixe` WHERE code_client = " . $code_client . " AND equipement <> '' ");
            $requete->execute();

            $total_equipement = 0;
            $i                = 0;

            while ($equipement = $requete->fetch(PDO::FETCH_OBJ)) {
                //vérification que la variable de la duree de financement soit bien remplie
                if ($equipement->duree_financement == 0 or $equipement->duree_financement == '') {
                    $duree_financement = 1;
                } else {
                    $duree_financement = $equipement->duree_financement;
                }

                //calcul des dates
                $date_fin_paiement       = strtotime($equipement->date_achat . " + " . $duree_financement . " month");
                $debut_mois_en_cours     = strtotime("first day of " . date("Y/m/d 00:00:00", time()));
                $debut_mois_achat        = strtotime("first day of " . $equipement->date_achat . " midnight");
                $debut_mois_fin_paiement = strtotime("first day of " . date("Y/m/d 00:00:00", $date_fin_paiement));

                // calcul des équipements a payer
                if ($debut_mois_en_cours < $debut_mois_fin_paiement and $debut_mois_en_cours >= $debut_mois_achat) {
                    $tab_equipement[$i]['date']               = $equipement->date_achat;
                    $tab_equipement[$i]['nom']                = $equipement->equipement;
                    $tab_equipement[$i]['quantite']           = $equipement->quantite;
                    $tab_equipement[$i]['prix']               = number_format($equipement->prix, 2);
                    $tab_equipement[$i]['financement']        = $duree_financement;
                    $tab_equipement[$i]['prix_finance']       = number_format($equipement->prix / $duree_financement, 2);
                    $tab_equipement[$i]['prix_finance_total'] = number_format($tab_equipement[$i]['prix_finance'] * $tab_equipement[$i]['quantite'], 2);
                    $tab_equipement[$i]['date_achat']         = $equipement->date_achat;

                    $total_equipement = number_format($total_equipement + $tab_equipement[$i]['prix_finance_total'], 2);

                    $i++;
                }
            }
            $requete->closeCursor();

            $l = 0;
            foreach ($detail_client as $Ligneclient => $forfait) {
                require "./inc/facture/fixe_calcul_base.php";
            }

            require "./inc/facture/fixe_calcul_consos.php";

            /**
             * Logiciel : exemple d'utilisation de HTML2PDF
             * 
             * Convertisseur HTML => PDF, utilise fpdf de Olivier PLATHEY 
             * Distribue sous la licence GPL. 
             *
             * @author		Laurent MINGUET <webmaster@spipu.net>
             */
            ob_start();
            ?>
            <page style="font-size: 12px" backtop="30mm" backbottom="30mm" backleft="15mm" >

                <page_header>
                    <div style="position: absolute; left: 50px"> 
                        <img src="./logo-facture/hto.png" >
                    </div>
                </page_header>

                <div style="position: absolute; left: 400px; top: 10px; font-size: 14px">
            <?php
            if ($donneesclients['raison_social'] == null) {
                echo $donneesclients['prenom'] . " " . $donneesclients['nom'];
                $nom = $donneesclients['prenom'] . " " . $donneesclients['nom'];
            } else {
                echo "<br>" . $donneesclients['raison_social'];
                $nom = $donneesclients['raison_social'];
            }
            echo "<br>" . $donneesclients['adresse'];
            echo "<br>" . $donneesclients['cp'] . " " . $donneesclients['ville'];
            ?>
                </div>

                <div style="position: absolute; left: 0px; top:150px; font-size: 12px">    
                    <?php
                    //reference client
                    echo 'Référence client: ' . $donneesclients['code_client_hto'];
                    echo '<br>Num Facture: f-' . date("Y") . date("m") . $donneesclients['code_client_hto'];
                    echo '<br>Date facturation: ' . date("01/m/Y");
                    //echo '<br>Date d\'échéance : '.date ("d/m/Y", mktime(0, 0, 0, date("m"),date("d")+30, date("Y")));
                    ?>
                </div>

                <div style="position: absolute; left: 0px; top:250px; font-size: 12px"> 
                    <?php require "./inc/facture/fixe_page_garde.php"; ?>
                </div>

                <page_footer>

            <?php
            echo $contenu;
            ?>	

                </page_footer> 
            </page>
            <page style="font-size: 12px" backtop="30mm" backbottom="30mm" backleft="15mm" >

                <page_header>
                    <div style="position: absolute; left: 50px"> 
                        <img src="./logo-facture/hto.png" >
                    </div>
                </page_header>


                <div style="position: absolute; left: 0px; top: 10px; font-size: 12px"> 
            <?php require "./inc/facture/fixe_affiche.php"; ?>
                </div>

                <page_footer>

            <?php
            echo $contenu;
            ?>

                </page_footer> 
            </page>
            <page style="font-size: 12px" backtop="30mm" backbottom="30mm" backleft="15mm">

                <page_header>
                    <div style="position: absolute; left: 50px"> 
                        <img src="./logo-facture/hto.png" >
                    </div>
                </page_header>

                <div style="position: absolute; left: 0px; top:10px; font-size: 10px">
            <?php require "./inc/facture/detail_facture_fixe.php"; ?>
                </div>

                <page_footer>

            <?php
            echo $contenu;
            ?>       
                </page_footer> 
            </page>

                    <?php
                    $dir  = "facture_temp/" . date("mY");
                    $dir2 = "facture/" . date("mY");
                    if (!is_dir($dir)) {
                        mkdir($dir);
                    }
                    if (!is_dir($dir2)) {
                        mkdir($dir2);
                    }
                    $content = ob_get_clean();
                    require_once(dirname(__FILE__) . '/../../lib/html2pdf/html2pdf.class.php');
                    $pdf     = new HTML2PDF('P', 'A4', 'fr', true, 'utf-8');
                    $pdf->WriteHTML($content, isset($_GET['vuehtml']));
                    if (is_dir($dir)) {
                        $pdf->Output($dir . "/Fixe-" . $donneesclients['code_client_hto'] . "-" . date("mY") . ".pdf", 'F');
                    } else {
                        mkdir($dir);
                        $pdf->Output($dir . "/Fixe-" . $donneesclients['code_client_hto'] . "-" . date("mY") . ".pdf", 'F');
                    }
                }
            }
            /**
             * Controleur permettant de lister les factures 
             */
            /*
              $requete = $bdd->prepare('SELECT * FROM admin_facture WHERE type = "fixe"');
              $requete->execute();
              $results=$requete->fetchall(PDO::FETCH_ASSOC);
              $requete->closeCursor();

              $requete = $bdd->query("SELECT SUM(total_facturation) AS total_facturation FROM admin_facture");
              $data = $requete->fetch();
              $total = number_format($data['total_facturation'],2);

              // Rendu de la page
              echo $twig->render('lancement-facture.html',
              array(	'factures' => $results,
              'total' => $total,
              'message' => $message,
              'error' => $error)); */
            redirect("lancement-facture");
        } else {
            redirect("home-admin");
        }